import axios from 'axios'
// import {Message} from 'element-ui'

// create an axios instance
const service = axios.create({
    baseURL: "api", // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        var token = localStorage.getItem('token');
        if (token) {
            config.headers.token = token
        } else if (!token && config.url !== '/users/login') {
            location.href = '/'
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data




        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

        return res

    },
    error => {
        console.log(1);
        console.log('err' + error) // for debug
        // Message({
        //     message: error.message,
        //     type: 'error',
        //     duration: 5 * 1000
        // })
        if (error.response && error.response.status === 406) {
            alert('登录过期,请重新登录')
            localStorage.removeItem('token')
            location.href = '/'
        } else if (error.response && error.response.status === 403) {
            alert('没有权限,请联系管理员')
        }else if (error.response && error.response.status === 501) {
            alert('后端接口异常')
        }
        return Promise.reject(error)
    }
)

export default service
